package main

import (
	"context"
	"github.com/go-redis/redis/v8"
	"go.uber.org/zap"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"

	"gLottery/internal/application/service"
	"gLottery/internal/infrastructure/logger"
	infraMysql "gLottery/internal/infrastructure/persistence/mysql"
	infraRedis "gLottery/internal/infrastructure/persistence/redis"
	"gLottery/internal/infrastructure/server"
	"gLottery/internal/interfaces/middleware"
	"gLottery/internal/interfaces/routes"
	"gLottery/pkg/config"
	"gLottery/pkg/jwt"
)

func main() {
	// 加载配置
	cfg, err := config.LoadConfig("./config/config.yaml")
	if err != nil {
		log.Fatal("cannot load config:", err)
	}

	// 初始化日志
	zapLogger, err := logger.NewZapLogger(&cfg.Logger)
	if err != nil {
		log.Fatal("cannot initialize logger:", err)
	}
	defer zapLogger.Sync()

	// 初始化MySQL
	db, err := gorm.Open(mysql.Open(cfg.Database.MySQL.DSN), &gorm.Config{})
	if err != nil {
		zapLogger.Fatal("failed to connect database", zap.Error(err))
	}
	//自动生成代码
	/*	if err := db.AutoMigrate(&model.User{}); err != nil {
		zapLogger.Fatal("failed to migrate database", zap.Error(err))
	}*/

	// 初始化Redis（实际使用时移除下划线）
	redisClient := redis.NewClient(&redis.Options{
		Addr:     cfg.Database.Redis.Addr,
		Password: cfg.Database.Redis.Password,
		DB:       cfg.Database.Redis.DB,
	})
	if _, err := redisClient.Ping(context.Background()).Result(); err != nil {
		zapLogger.Fatal("failed to connect redis", zap.Error(err))
	}
	cacheRepo := infraRedis.NewCacheRepository(redisClient) // 明确标记待使用

	// 初始化仓储
	userRepo := infraMysql.NewUserRepository(db)

	// 初始化服务
	jwtService := jwt.NewJWTService(cfg.JWT.Secret, cfg.JWT.Timeout)
	userService := service.NewUserService(userRepo, cacheRepo, jwtService)

	// 创建Gin服务器（注入logger）
	ginServer := server.NewGinServer(cfg.Server.Mode, zapLogger)

	// 注册中间件
	authMiddleware := middleware.NewAuth(jwtService)

	// 注册路由
	routes.RegisterUserRoutes(ginServer.Engine, userService, authMiddleware)

	// 启动服务器
	zapLogger.Info("Starting server",
		zap.String("mode", cfg.Server.Mode),
		zap.Int("port", cfg.Server.Port))

	if err := ginServer.Run(cfg.Server.Port); err != nil {
		zapLogger.Fatal("failed to start server", zap.Error(err))
	}
}
